package com.synjones.zeuscloudserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.synjones.core.util.StringUtil;
import com.synjones.zeus.model.ExReqBean;
import com.synjones.zeus.model.ExRespBean;
import com.synjones.zeus.model.StatusInfo;
import com.synjones.zeus.model.authorize.*;
import com.synjones.zeuscloudserver.config.MyConfig;
import com.synjones.zeuscloudserver.eureka.ZeusYktService;
import com.synjones.zeuscloudserver.mapper.AuthorizeMapper;
import com.synjones.zeuscloudserver.mapper.TerminalMapper;
import com.synjones.zeuscloudserver.service.AuthorizeService;
import com.synjones.zeuscloudserver.util.ccl.util.G4Utils;
import com.synjones.zeuscloudserver.util.encrypt.AESUtils;
import com.synjones.zeuscloudserver.util.encrypt.DigestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.synjones.zeus.model.CodeStr.*;

/**
 * @author Think 2018/5/22 11:49
 */
@Service
public class AuthorizeServiceImpl implements AuthorizeService {

    private final static Logger logger = LoggerFactory.getLogger
            (AuthorizeServiceImpl.class);

    @Resource
    private AuthorizeMapper authorizeMapper;
    @Resource
    private ZeusYktService zeusYktService;
    @Resource
    private TerminalMapper terminalMapper;
    @Resource
    private MyConfig myConfig;

    @Override
    public ExRespBean<String> authorizeDevice(ExReqBean<AuthorizeReqBean> reqBean) {
        logger.info("授权收到请求：{}", JSON.toJSONString(reqBean));
        AuthorizeResBean authorizeResBean;
        try {
            // header中包含组织机构码，通过组织机构码去数据库lisence表中查出用户名、密码、数量
            AuthorizeLisence authorizeLisence = authorizeMapper.getLisenceInfo(reqBean.getOrganizationCode());
            // 组织机构码为null时直接返回授权失败
            if (G4Utils.isEmpty(authorizeLisence)) {
                logger.info("组织机构查询不到：{}", reqBean.getOrganizationCode());
                return new ExRespBean<>(StatusInfo._1103.code(), StatusInfo._1103.desc());
            }else{
                authorizeLisence.setPassWord(G4Utils.decryptBasedDes(authorizeLisence.getPassWord()));
                authorizeLisence.setAuthenPwd(G4Utils.decryptBasedDes(authorizeLisence.getAuthenPwd()));
            }
            // Sha1加密用户名及密码
            String sha1UserName = DigestUtil.hmacSha1(authorizeLisence.getUserName(), myConfig.getSha1());
            String sha1PassWord = DigestUtil.hmacSha1(authorizeLisence.getPassWord(), myConfig.getSha1());
            // 比较传入的用户名及密码和后端的用户名是否相等
            if (sha1UserName.equals(reqBean.getData().getUserName()) && sha1PassWord.equals(reqBean.getData().getPassWord())) {
                // 查询设备imei列表
                List<String> list = authorizeMapper.getImeiByOrgCode(reqBean.getOrganizationCode());
                // 判断列表数量和授权设备最大数量的大小
                if (list.size() < authorizeLisence.getCount()) {
                    if (list.contains(reqBean.getImei())) {
                        //验证一卡通系统中是否有这个设备
                        ExRespBean verifyTsmRegFactorRet = verifyTsmRegFactor(reqBean);
                        if (!verifyTsmRegFactorRet.statusOk()) {
                            return verifyTsmRegFactorRet;
                        }
                        authorizeResBean = authorizeMapper.getTimeByImei(reqBean.getImei(), reqBean.getOrganizationCode());
                        return new ExRespBean<>(StatusInfo._1102.code(), StatusInfo._1102.desc(),
                                AESUtils.encrypt(JSON.toJSONString(authorizeResBean), myConfig.getEncryption()));
                    } else {
                        Date startTime = new Date(System.currentTimeMillis());
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(startTime);
                        calendar.add(Calendar.YEAR, 1);
                        Date endTime = calendar.getTime();
                        //获取此OrgCode下最大的设备类型编号
                        String serialNumber = authorizeMapper.getMaxSNByOrgCodeTerminalType(reqBean.getOrganizationCode(),reqBean.getData().getTerminalType());
                        if(G4Utils.isEmpty(serialNumber)){
                            if(reqBean.getData().getTerminalType().equals(NUM1)){
                                serialNumber = "LD-1";
                            } else if(reqBean.getData().getTerminalType().equals(NUM2)){
                                serialNumber = "LF-1";
                            }else if(reqBean.getData().getTerminalType().equals(NUM3)){
                                serialNumber = "TD-1";
                            }else if(reqBean.getData().getTerminalType().equals(NUM4)){
                                serialNumber = "TF-1";
                            } else if(reqBean.getData().getTerminalType().equals(NUM5)){
                                serialNumber = "GD-1";
                            } else if(reqBean.getData().getTerminalType().equals(NUM6)){
                                serialNumber = "GF-1";
                            }
                        }else{
                            String[] serialN = serialNumber.split("-");
                            serialNumber = serialN[0] + (Integer.parseInt(serialN[1] + 1));
                        }
                        authorizeMapper.insertAuthorize(new AuthorizeInfo(reqBean.getImei(), reqBean.getOrganizationCode(),
                                G4Utils.Date2String(startTime,"yyyy-MM-dd HH:mm:ss"),
                                G4Utils.Date2String(endTime,"yyyy-MM-dd HH:mm:ss"),
                                authorizeLisence.getAuthenName(),authorizeLisence.getAuthenPwd(), reqBean.getData().getTerminalType(),serialNumber));
                        authorizeResBean = authorizeMapper.getTimeByImei(reqBean.getImei(), reqBean.getOrganizationCode());
                        authorizeResBean.setStartTime(String.valueOf(stringDateToLong(authorizeResBean.getStartTime())));
                        authorizeResBean.setEndTime(String.valueOf(stringDateToLong(authorizeResBean.getEndTime())));
                        //验证一卡通系统中是否有这个设备
                        ExRespBean verifyTsmRegFactorRet = verifyTsmRegFactor(reqBean);
                        if (!verifyTsmRegFactorRet.statusOk()) {
                            return verifyTsmRegFactorRet;
                        }
                        return new ExRespBean<>(StatusInfo._1102.code(), StatusInfo._1102.desc(),
                                AESUtils.encrypt(JSON.toJSONString(authorizeResBean), myConfig.getEncryption()));
                    }
                }
                if (list.size() == authorizeLisence.getCount()) {
                    if (list.contains(reqBean.getImei())) {
                        //验证一卡通系统中是否有这个设备
                        ExRespBean verifyTsmRegFactorRet = verifyTsmRegFactor(reqBean);
                        if (!verifyTsmRegFactorRet.statusOk()) {
                            return verifyTsmRegFactorRet;
                        }
                        authorizeResBean = authorizeMapper.getTimeByImei(reqBean.getImei(), reqBean.getOrganizationCode());
                        authorizeResBean.setStartTime(String.valueOf(stringDateToLong(authorizeResBean.getStartTime())));
                        authorizeResBean.setEndTime(String.valueOf(stringDateToLong(authorizeResBean.getEndTime())));
                        return new ExRespBean<>(StatusInfo._1102.code(), StatusInfo._1102.desc(),
                                AESUtils.encrypt(JSON.toJSONString(authorizeResBean), myConfig.getEncryption()));
                        } else {
                        return new ExRespBean<>(StatusInfo._1103.code(), StatusInfo._1103.desc());
                    }
                }
            } else {
                logger.info("用户名密码验证失败：{},{},{},{}", sha1UserName, reqBean.getData().getUserName(), sha1PassWord, reqBean.getData().getPassWord());
            }
            return new ExRespBean<>(StatusInfo._1103.code(), StatusInfo._1103.desc());
        } catch (Exception ex) {
            logger.error("{}", ex);
            return new ExRespBean<>(StatusInfo._1103.code(), StatusInfo._1103.desc());
        }
    }
 /**
   *  格式化时间
   *  @param date
   *  @author yys
   *  Description: 格式化时间
   *  @date 11:27 2018-07-09
   *  @return long longTime
   */
    private long stringDateToLong(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long longTime = 0;
        try {
            longTime = sdf.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return longTime;
    }

    /**
     * 去一卡通验证设备的注册因子
     *
     * @param reqBean
     * @return
     */
    private ExRespBean<RegFactorBean> verifyTsmRegFactor(ExReqBean<AuthorizeReqBean> reqBean) {
        logger.info("验证授权因子收到请求：{}", JSON.toJSONString(reqBean));
        ExReqBean<RegFactorReqBean> regReqBean = new ExReqBean<>();
        BeanUtils.copyProperties(reqBean, regReqBean);
        RegFactorReqBean regFactorReqBean = new RegFactorReqBean(reqBean.getImei(), regReqBean.getOrganizationCode());
        regReqBean.setData(regFactorReqBean);
        ExRespBean<RegFactorBean> respBean = zeusYktService.regFactor(regReqBean);
        logger.info("验证授权因子响应：{}", JSON.toJSONString(respBean));
        if (respBean.statusOk() && !StringUtil.isNullOrEmpty(respBean.getData().getPnretcode())) {
            return respBean;
        }
        return new ExRespBean(StatusInfo._1103.code(), StatusInfo._1103.desc());
    }
}
